import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import Layout from '@/layout/index.vue'
import store from '@/store'
Vue.use(VueRouter)
const whiteList = ['/login']

const routes: Array<RouteConfig> = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/',
    name: 'layout',
    component: Layout,
    children: [
      {
        path: '/',
        name: 'Home',
        component: () => import('@/views/home/index.vue')
      },
      {
        path: '/advert',
        name: 'advert',
        component: () => import('@/views/advert/index.vue')
      },
      {
        path: '/advert-space',
        name: 'advert-space',
        component: () => import('@/views/advert-space/index.vue')
      },
      {
        path: '/course',
        name: 'course',
        component: () => import('@/views/course/index.vue')
      },
      {
        path: '/menu',
        name: 'menu',
        component: () => import('@/views/menu/index.vue')
      },
      {
        path: '/resource',
        name: 'resource',
        component: () => import('@/views/resource/index.vue')
      },
      {
        path: '/role',
        name: 'role',
        component: () => import('@/views/role/index.vue')
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('@/views/user/index.vue')
      },
      {
        path: '/menu/create',
        name: 'menu-create',
        component: () => import('@/views/menu/create.vue')
      },
      {
        path: '/role/:roleId/alloc-menu',
        name: 'alloc-menu',
        component: () => import('@/views/role/alloc-menu.vue'),
        props: true
      },
      {
        path: '/role/:roleId/alloc-resource',
        name: 'alloc-resource',
        component: () => import('@/views/role/alloc-resource.vue'),
        props: true
      }
    ]
  },
  {
    path: '*',
    name: '404',
    component: () => import('@/views/404.vue')
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (store.state.user) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`)
    }
  }
})

export default router
